package com.rescue.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.rescue.toolbean.JDBC;
import com.mysql.jdbc.Connection;
import java.sql.*;

/**
 * Servlet implementation class RegServlet
 */
@WebServlet("/RegServlet")
public class RegServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
			try {
				Connection conn=JDBC.getConnection();
			PreparedStatement pStmt=conn.prepareStatement("select idnumber from user where idnumber=?");
			pStmt.setString(1, request.getParameter("idnumber"));
			ResultSet rs=pStmt.executeQuery();
			System.out.println(rs);
			if(!rs.next()) {
				PreparedStatement Stmt=conn.prepareStatement("insert into user(idnumber,userpwd,certificate)values(?,?,?)");
				Stmt.setString(1,  request.getParameter("idnumber"));
				Stmt.setString(2,  request.getParameter("userpwd"));
				Stmt.setString(3,  request.getParameter("certificate"));
	
				int rtn=Stmt.executeUpdate();
				System.out.println(rtn);
				HttpSession session=request.getSession();
				session.setAttribute("idnumber", request.getParameter("idnumber").toString());
				session.setAttribute("userpwd", request.getParameter("userpwd").toString());
				session.setAttribute("certificate", request.getParameter("certificate").toString());
				response.sendRedirect("MessageBoard.jsp");

				//request.getRequestDispatcher("/MessageBoard.jsp").forward(request,response);//TODO 到时候转到相应的	
				
			}
			response.sendRedirect("RegisterFalse.jsp");
			JDBC.closeStament(rs, pStmt, conn);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	
			
		
		
	}

}
